package com.example.singing.manager;

import com.example.singing.model.SystemConfig;
import com.example.singing.util.FileUtil;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 系统配置管理器
 * 负责系统配置的保存、加载、备份和恢复
 */
public class SystemConfigManager {
    private static final String CONFIG_FILE = "system_config.dat";
    private static final String BACKUP_DIR = "backups";
    private SystemConfig config;
    
    public SystemConfigManager() {
        loadConfig();
    }
    
    /**
     * 获取系统配置
     */
    public SystemConfig getConfig() {
        return config;
    }
    
    /**
     * 保存系统配置
     */
    public boolean saveConfig() {
        try {
            config.setLastModified(LocalDateTime.now());
            FileUtil.saveData(config, CONFIG_FILE);
            config.addSystemLog("系统配置已保存");
            return true;
        } catch (Exception e) {
            System.err.println("保存系统配置失败: " + e.getMessage());
            config.addSystemLog("保存系统配置失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 加载系统配置
     */
    @SuppressWarnings("unchecked")
    private void loadConfig() {
        try {
            Object data = FileUtil.loadData(CONFIG_FILE);
            if (data != null && data instanceof SystemConfig) {
                config = (SystemConfig) data;
                config.addSystemLog("系统配置已加载");
            } else {
                // 创建默认配置
                config = new SystemConfig();
                config.addSystemLog("创建默认系统配置");
                saveConfig();
            }
        } catch (Exception e) {
            System.err.println("加载系统配置失败: " + e.getMessage());
            config = new SystemConfig();
            config.addSystemLog("加载系统配置失败，使用默认配置: " + e.getMessage());
        }
    }
    
    /**
     * 更新配置并保存
     */
    public boolean updateConfig(SystemConfig newConfig) {
        this.config = newConfig;
        return saveConfig();
    }
    
    /**
     * 重置配置为默认值
     */
    public boolean resetToDefaults() {
        config.resetToDefaults();
        config.addSystemLog("系统配置已重置为默认值");
        return saveConfig();
    }
    
    /**
     * 创建数据备份
     */
    public String createBackup() {
        try {
            // 确保备份目录存在
            File backupDir = new File(BACKUP_DIR);
            if (!backupDir.exists()) {
                backupDir.mkdirs();
            }
            
            // 生成备份文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String backupFileName = "backup_" + timestamp + ".zip";
            String backupPath = BACKUP_DIR + File.separator + backupFileName;
            
            // 创建ZIP备份
            try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(Paths.get(backupPath)))) {
                // 备份数据文件
                String[] dataFiles = {"users.dat", "teams.dat", "competitions.dat", "scores.dat", CONFIG_FILE};
                for (String fileName : dataFiles) {
                    File file = new File(fileName);
                    if (file.exists()) {
                        ZipEntry zipEntry = new ZipEntry(fileName);
                        zipOut.putNextEntry(zipEntry);
                        Files.copy(file.toPath(), zipOut);
                        zipOut.closeEntry();
                    }
                }
                
                // 备份用户上传的图片
                File uploadDir = new File("user_uploads");
                if (uploadDir.exists() && uploadDir.isDirectory()) {
                    File[] uploadFiles = uploadDir.listFiles();
                    if (uploadFiles != null) {
                        for (File uploadFile : uploadFiles) {
                            if (uploadFile.isFile()) {
                                ZipEntry zipEntry = new ZipEntry("user_uploads/" + uploadFile.getName());
                                zipOut.putNextEntry(zipEntry);
                                Files.copy(uploadFile.toPath(), zipOut);
                                zipOut.closeEntry();
                            }
                        }
                    }
                }
            }
            
            // 记录备份信息
            config.addBackupRecord(backupPath);
            config.addSystemLog("数据备份已创建: " + backupPath);
            saveConfig();
            
            // 清理旧备份
            cleanupOldBackups();
            
            return backupPath;
        } catch (Exception e) {
            System.err.println("创建备份失败: " + e.getMessage());
            config.addSystemLog("创建备份失败: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 清理旧备份文件
     */
    private void cleanupOldBackups() {
        try {
            File backupDir = new File(BACKUP_DIR);
            if (!backupDir.exists()) return;
            
            File[] backupFiles = backupDir.listFiles((dir, name) -> name.startsWith("backup_") && name.endsWith(".zip"));
            if (backupFiles == null) return;
            
            // 按修改时间排序，删除最旧的文件
            List<File> sortedFiles = new ArrayList<>();
            for (File file : backupFiles) {
                sortedFiles.add(file);
            }
            sortedFiles.sort((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));
            
            // 删除超出限制的备份文件
            int maxBackups = config.getMaxBackupFiles();
            while (sortedFiles.size() > maxBackups) {
                File oldBackup = sortedFiles.remove(0);
                if (oldBackup.delete()) {
                    config.addSystemLog("已删除旧备份: " + oldBackup.getName());
                }
            }
        } catch (Exception e) {
            System.err.println("清理旧备份失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取系统状态信息
     */
    public SystemStatus getSystemStatus() {
        SystemStatus status = new SystemStatus();
        
        // 检查数据文件
        status.usersCount = getFileRecordCount("users.dat");
        status.teamsCount = getFileRecordCount("teams.dat");
        status.competitionsCount = getFileRecordCount("competitions.dat");
        status.scoresCount = getFileRecordCount("scores.dat");
        
        // 检查磁盘空间
        File rootDir = new File(".");
        status.totalSpace = rootDir.getTotalSpace();
        status.freeSpace = rootDir.getFreeSpace();
        status.usedSpace = status.totalSpace - status.freeSpace;
        
        // 检查备份文件
        File backupDir = new File(BACKUP_DIR);
        if (backupDir.exists()) {
            File[] backupFiles = backupDir.listFiles((dir, name) -> name.endsWith(".zip"));
            status.backupCount = backupFiles != null ? backupFiles.length : 0;
        }
        
        // 检查用户上传文件
        File uploadDir = new File("user_uploads");
        if (uploadDir.exists()) {
            File[] uploadFiles = uploadDir.listFiles();
            status.uploadFilesCount = uploadFiles != null ? uploadFiles.length : 0;
        }
        
        status.lastBackup = config.getRecentBackups().isEmpty() ? 
            "无" : config.getRecentBackups().get(config.getRecentBackups().size() - 1);
        
        return status;
    }
    
    /**
     * 获取文件记录数量（简单估算）
     */
    private int getFileRecordCount(String fileName) {
        try {
            File file = new File(fileName);
            if (!file.exists()) return 0;
            
            // 简单估算：假设每个记录大约100字节
            long fileSize = file.length();
            return (int) (fileSize / 100);
        } catch (Exception e) {
            return 0;
        }
    }
    
    /**
     * 系统状态信息类
     */
    public static class SystemStatus {
        public int usersCount;
        public int teamsCount;
        public int competitionsCount;
        public int scoresCount;
        public int backupCount;
        public int uploadFilesCount;
        public long totalSpace;
        public long freeSpace;
        public long usedSpace;
        public String lastBackup;
        
        public double getUsedSpacePercentage() {
            if (totalSpace == 0) return 0;
            return (double) usedSpace / totalSpace * 100;
        }
        
        public String getFormattedTotalSpace() {
            return formatBytes(totalSpace);
        }
        
        public String getFormattedFreeSpace() {
            return formatBytes(freeSpace);
        }
        
        public String getFormattedUsedSpace() {
            return formatBytes(usedSpace);
        }
        
        private String formatBytes(long bytes) {
            if (bytes < 1024) return bytes + " B";
            if (bytes < 1024 * 1024) return String.format("%.1f KB", bytes / 1024.0);
            if (bytes < 1024 * 1024 * 1024) return String.format("%.1f MB", bytes / (1024.0 * 1024));
            return String.format("%.1f GB", bytes / (1024.0 * 1024 * 1024));
        }
    }
    
    /**
     * 导出配置到文件
     */
    public boolean exportConfig(String filePath) {
        try {
            FileUtil.saveData(config, filePath);
            config.addSystemLog("配置已导出到: " + filePath);
            return true;
        } catch (Exception e) {
            System.err.println("导出配置失败: " + e.getMessage());
            config.addSystemLog("导出配置失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 从文件导入配置
     */
    public boolean importConfig(String filePath) {
        try {
            Object data = FileUtil.loadData(filePath);
            if (data instanceof SystemConfig) {
                this.config = (SystemConfig) data;
                config.addSystemLog("配置已从文件导入: " + filePath);
                return saveConfig();
            } else {
                config.addSystemLog("导入配置失败: 文件格式不正确");
                return false;
            }
        } catch (Exception e) {
            System.err.println("导入配置失败: " + e.getMessage());
            config.addSystemLog("导入配置失败: " + e.getMessage());
            return false;
        }
    }
}
